package com.party.jackclientandroid;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.party.jackclientandroid.api.CommonService;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.base.MyException;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.AppInfo;
import com.party.jackclientandroid.bean.RegisterInfo;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.bean.VerCode;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.VerCodeTimer;
import com.party.jackclientandroid.event.AuthResultEvent;
import com.party.jackclientandroid.event.LoginEvent;
import com.party.jackclientandroid.event.ReLoginSuccessEvent;
import com.party.jackclientandroid.utils.CommonUtil;
import com.party.jackclientandroid.utils.PhoneUtil;
import com.party.jackclientandroid.wxapi.WXPayUtils;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_account)
    EditText mPhoneEdit;
    @BindView(R.id.et_code)
    EditText mVerCodeEdit;
    @BindView(R.id.getVerCodeBtn)
    Button getVerCodeBtn;

    VerCodeTimer mVerCodeTimer;
    UserService userService;
    String phone;
    private boolean isTokenEmpty;
    AppInfo mAppInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        EventBus.getDefault().register(this);
        initData();
    }

    private void getPhoneNum(){
        TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();//获取智能设备唯一编号
        String te1  = tm.getLine1Number();//获取本机号码
        String imei = tm.getSimSerialNumber();//获得SIM卡的序号
        String imsi = tm.getSubscriberId();//得到用户Id
    }

    protected void initData() {
        userService = new UserService(this);
        getAppId();
    }

    @OnClick({R.id.register_btn, R.id.onceLogin})
    public void handleClickSth(View view) {
        if (dupCommit()) return;
        switch (view.getId()) {
            case R.id.register_btn:
                Intent intent = new Intent();
                intent.putExtra("appInfo", mAppInfo);
                startActivity(RegisterActivity.class, intent);
                break;
            case R.id.onceLogin:
                getWxCode();
                break;
        }
    }

    public void getWxCode() {
        try {
            WXPayUtils build = new WXPayUtils.WXPayBuilder().build();
            build.getUserCode(mActivity, mAppInfo.getWxAppId());
        } catch (MyException e) {
            showToast(e.getMessage());
        }
    }


    /**
     * 微信授权成功,回调
     *
     * @param authResultEvent
     */
    @Subscribe(priority = 99)//注册优先级 100 登录是 99
    public void authFinish(AuthResultEvent authResultEvent) {
        //收到消息后，默认取消广播事件
        EventBus.getDefault().cancelEventDelivery(authResultEvent);
        onceLogin(authResultEvent.getCode());
    }


    public void onceLogin(String code) {
        addDisposableIoMain(userService.wxLogin(code), new DefaultConsumer<User>(mApplication) {
            @Override
            public void operateError(BaseResult<User> baseBean) {
                DialogController.showConfirmDialog(mActivity, "提示", baseBean.getMessage(), "立即注冊", (View v) -> {
                    startActivity(RegisterActivity.class);
                });
            }

            @Override
            public void operateSuccess(BaseResult<User> baseBean) {
                handleLoginInfo(baseBean);
            }
        });
    }


    /**
     * 获取一键登录信息。
     */
    private void getAppId() {
        showLoadingDialog();
        addDisposableIoMain(userService.getAppId(), new DefaultConsumer<AppInfo>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<AppInfo> baseBean) {
                mAppInfo = baseBean.getData();
                hideAlertDialog();
            }
        });
    }


    /**
     * 获取验证码
     */
    @OnClick(R.id.getVerCodeBtn)
    public void clickGetVerCode() {
        if (dupCommit(5000)) return;
        phone = mPhoneEdit.getText().toString();
        if (!PhoneUtil.isMobileNO(phone)) {
            showToast("号码格式有误");
            return;
        }
        addDisposableIoMain(userService.getVerCode(phone), new DefaultConsumer<VerCode>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<VerCode> baseBean) {
                mVerCodeTimer = new VerCodeTimer(userService.second, getVerCodeBtn);
                mVerCodeTimer.setChangeView(mPhoneEdit, getVerCodeBtn);
                mVerCodeTimer.start();
            }
        });
    }


    /**
     * 登录
     */
    @OnClick(R.id.btn_login)
    public void login() {
        if (dupCommit()) return;
        String phone = mPhoneEdit.getText().toString();
        String verCode = mVerCodeEdit.getText().toString();
        if (!PhoneUtil.isMobileNO(phone)) {
            showToast("号码格式有误");
            return;
        }
        if (verCode.trim().length() != 4) {
            showToast("请输入验证码");
            return;
        }
        if (this.phone == phone) {
            showToast("请重新获取验证码");
            return;
        }
        showLoadingDialog("正在登录...");
        String addressCode = mApplication.getMap().getAdCode();
        addDisposableIoMain(userService.loginUser(phone, verCode, addressCode), new DefaultConsumer<User>(mApplication) {

            @Override
            public void operateSuccess(BaseResult<User> baseBean) {
                hideAlertDialog();
                handleLoginInfo(baseBean);
            }
        });
    }

    public void handleLoginInfo(BaseResult<User> baseBean) {
        User user = baseBean.getData();
        if (TextUtils.isEmpty(mApplication.getToken())) {
            isTokenEmpty = true;
        } else {
            isTokenEmpty = false;
        }
        if (user != null) {
            mApplication.setUser(user);
            loginSuccess();
        } else {
            showToast("数据有误");
        }
    }

    /**
     * 登录成功
     */
    private void loginSuccess() {
        if (!isTokenEmpty) {
            mApplication.removeStackSecondActivity(1);
        }
        if (!mApplication.hasContainActivity(MainActivity.class)) {
            Intent intent = new Intent(mActivity, MainActivity.class);
            intent.putExtra("msg", 1);
            startActivity(intent);
        }
        mApplication.post(new ReLoginSuccessEvent());
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mVerCodeTimer != null) {
            mVerCodeTimer.cancel();
            mVerCodeTimer = null;
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        EventBus.getDefault().post(new LoginEvent(true));
    }
}
